<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="关联对象">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入关联对象"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="方案名称">
          <el-input
            v-model="queryParams.planName"
            placeholder="请输入方案名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="custom_card">
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="addfangan"
            >新增返佣方案</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column
          label="关联业务"
          min-width="160"
          align="center"
          prop="associatedBusinessName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="关联方式"
          min-width="160"
          align="center"
          prop="connectionWayName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="关联对象"
          min-width="240"
          align="center"
          prop="associationModeName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="方案名称"
          min-width="160"
          align="center"
          prop="planName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="一级佣金/元"
          min-width="180"
          align="center"
          prop="primaryCommissionAmount"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="二级佣金/元"
          min-width="180"
          align="center"
          prop="secondaryCommissionAmount"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          min-width="180"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="180"
          align="center"
          class-name="small-padding fixed-width"
          fixed="left"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handDetail(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" type="text" @click="handEdit(scope.row)"
              >修改</el-button
            >
            <el-button size="mini" type="text" @click="handDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 新增方案 -->
    <el-dialog :title="title" width="600px" :visible.sync="showxinzheng">
      <el-form
        label-width="80px"
        :model="form"
        ref="form"
        :rules="rules"
        :key="mivaKey"
      >
        <el-form-item label="关联业务" prop="associatedBusinessNo">
          <el-select
            v-model="form.associatedBusinessNo"
            @change="yewuchange"
            style="width: 100%"
          >
            <template v-for="(item, index) in dict.type.commission_type">
              <el-option
                :label="item.label"
                :value="item.value"
                :key="index"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="关联方式" prop="connectionWayNo">
          <el-select
            v-model="form.connectionWayNo"
            @change="fangshichange"
            style="width: 100%"
          >
            <template v-for="(item, index) in connectionWayList">
              <el-option
                :label="item.busName"
                :value="String(item.busId)"
                :key="index"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item :label="`关联${form.connectionWayName}`" prop="planName">
          <el-select
            v-model="select"
            multiple
            placeholder="请选择"
            @change="sanjichange"
            style="width: 100%"
          >
            <template v-for="(item, index) in sanjilist">
              <el-option
                :label="item.associationModeName"
                :value="item.associationModeId"
                :key="index"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="返佣方案" prop="planName2">
          <el-button @click="shoufananyongjin = true">{{
            planName || '请选择'
          }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addsave">确 定</el-button>
        <el-button @click="showxinzheng = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="返佣方案选择"
      width="950px"
      :visible.sync="shoufananyongjin"
    >
      <fanganyongjin @select="selectfanganyongjin"></fanganyongjin>
    </el-dialog>

    <!-- 查看详情 -->
    <el-dialog
      title="查看详情"
      width="900px"
      :visible.sync="showxiangiqng"
      @close="xiangqing"
    >
      <el-descriptions border>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="关联业务">{{
          xiangqing.associatedBusinessName
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="关联方式">{{
          xiangqing.connectionWayName
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="关联商品">{{
          xiangqing.associationModeName
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="返佣方案">{{
          xiangqing.planName
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="一级佣金/元">{{
          xiangqing.primaryCommissionAmount || 0
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="二级分佣金额(元)">{{
          xiangqing.secondaryCommissionAmount || 0
        }}</el-descriptions-item>
        <el-descriptions-item label-class-name="my-descriptions-label"  :span="2" label="创建时间">{{
          xiangqing.createTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listMkOrder, exportMkOrder } from '@/api/marketing/mkOrder'
import * as CommissionApi from '@/api/marketing/commission.js'
import * as QmyxApi from '@/api/marketing/qmyx.js'
import fanganyongjin from './components/fanganyongjin.vue'

export default {
  name: 'MkOrder',
  components: {
    fanganyongjin,
  },
  dicts: ['commission_type', 'businss_mode'],
  data() {
    const validatecommissionId = (rule, value, callback) => {
      if (!this.form.commissionId) {
        callback(new Error('请选择方案'))
      } else {
        callback()
      }
    }
    const validateconnectionWayNo = (rule, value, callback) => {
      if (
        this.form.associationModeDto == [] ||
        this.form.associationModeDto.length == 0
      ) {
        callback(new Error('请选择关联方式'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 全名营销订单表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: '', // planName
        planName: '', // 方案名称
      },
      shoufananyongjin: false,
      showxinzheng: false,
      planName: '请选择',
      // 表单参数
      form: {
        associatedBusinessNo: '', // 关联业务编号（数据字典维护）
        associatedBusinessName: '', // 关联业务名称（数据字典维护）
        connectionWayNo: '', // 关联方式编号
        connectionWayName: '', // 关联方式名称
        commissionId: '', // 佣金方案id
        associationModeDto: [
          // {
          //     associationModeId: "xxxxxx", // 关联方案/车型/品类/活动id
          //     associationModeName: "xxxxxx", // 关联方案/车型/品类/活动名称
          // },
        ], // 关联业务
      },
      // 表单校验
      rules: {
        planName: [
          {
            required: true,
            message: '请选择关联数据',
            trigger: 'change',
            validator: validateconnectionWayNo,
          },
        ],
        associatedBusinessNo: [
          { required: true, message: '关联业务不能为空', trigger: 'change' },
        ],
        connectionWayNo: [
          { required: true, message: '关联方式不能为空', trigger: 'change' },
        ],
        planName2: [
          {
            required: true,
            message: '返佣方案不能为空',
            trigger: 'change',
            validator: validatecommissionId,
          },
        ],
      },
      select: [],
      isEdit: false,
      showxiangiqng: false,
      xiangqing: {},
      checkboxGroup1: [],
      connectionWayList: [],
      bessusinList: [], //租售业务类型
      planList: [], // 租售方案
      modelList: [], // 租售车型
      getZsSystemActivityData: [], // 营销系统获取活动
      sanjilist: [], // 三级列表
      sanjimap: {}, // 三级映射
      sanjimap2: {}, // 三级映射2
      mivaKey: 0,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询全名营销订单列表 */
    getList() {
      this.loading = true
      QmyxApi.list(this.queryParams).then((response) => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        createTime: '', // 创建时间
        planName: '', // 方案名称
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.handleQuery()
    },
    /** 详情按钮操作 */
    handDetail(row) {
      QmyxApi.detail(row.id).then((res) => {
        this.showxiangiqng = true
        this.xiangqing = res.data
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log(this.$download.mmvExcel)
      const queryParams = this.queryParams
      this.$modal
        .confirm('是否确认导出所有全名营销订单数据项？')
        .then(() => {
          this.exportLoading = true
          return QmyxApi.exportaa(queryParams)
        })
        .then((response) => {
          this.$download.mmvExcel(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },
    /**
     * 创建方案
     */
    addfangan() {
      this.resetFrom()
      //this.$refs.form.resetFields()
      this.title = '新增返佣方案'
      this.form = {
        associatedBusinessNo: '', // 关联业务编号（数据字典维护）
        associatedBusinessName: '', // 关联业务名称（数据字典维护）
        connectionWayNo: '', // 关联方式编号
        connectionWayName: '', // 关联方式名称
        commissionId: '', // 佣金方案id
        associationModeDto: [], // 关联业务
      }
      this.planName = '请选择'
      this.select = []
      this.showxinzheng = true
    },
    /**
     * 提交创建方案
     */
    addsave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            QmyxApi.put(this.form).then((res) => {
              this.$message.success(res.msg)
              this.showxinzheng = false
              this.handleQuery()
            })
            return
          }
          QmyxApi.add(this.form).then((res) => {
            console.log(res)
            this.$message.success(res.msg)
            this.showxinzheng = false
            this.handleQuery()
          })
        }
      })
    },
    resetFrom() {
      this.form = {
        associatedBusinessNo: '', // 关联业务编号（数据字典维护）
        associatedBusinessName: '', // 关联业务名称（数据字典维护）
        connectionWayNo: '', // 关联方式编号
        connectionWayName: '', // 关联方式名称
        commissionId: '', // 佣金方案id
        associationModeDto: [], // 关联业务
      }
      this.isEdit = false
    },
    /**
     * 编辑
     */
    async handEdit(row) {
      this.resetFrom()
      this.title = '编辑返佣方案'
      this.form = row
      this.planName = row.planName
      this.showxinzheng = true
      this.isEdit = true
      var connectionWayName = this.form.connectionWayName
      var connectionWayNo = this.form.connectionWayNo
      this.yewuchange(this.form.associatedBusinessNo)
      this.form.connectionWayName = connectionWayName
      this.form.connectionWayNo = connectionWayNo
      await this.fangshichange()
      //
      const aaa = this.form.associationModeName.split(',')
      this.select = aaa.map((val) => {
        return this.sanjimap2[val]?.associationModeId
      })
      this.sanjichange()
      this.mivaKey++
    },
    /** 各种状态弹窗操作 */
    handleConfirm(data, callback) {
      this.$modal.confirm(data.msg).then((e) => {
        callback()
      })
    },
    /**
     * 删除
     */
    handDel(row) {
      this.handleConfirm({ msg: '确定要删除返佣方案？' }, (e) => {
        QmyxApi.del(row.id).then((res) => {
          this.$message.success(res.msg)
          this.showxinzheng = false
          // this.handleQuery();
          // this.handleQuery();
          this.getList()
        })
      })
    },
    yewuchange(data) {
      // this.form.associationModeDto=[];
      const item = this.dict.type.commission_type.find(
        (val) => val.value == data
      )
      this.form.associatedBusinessName = item.label
      this.form.connectionWayName = ''
      this.form.connectionWayNo = ''
      QmyxApi.connectionWayList(item.raw.dictCode).then((res) => {
        this.connectionWayList = res.data
      })
      this.select = []
    },
    async fangshichange() {
      // this.form.associationModeDto=[];
      this.form.connectionWayName =
        this.connectionWayList.find(
          (val) => val.busId == this.form.connectionWayNo
        )?.busName || ''
      if (this.form.associatedBusinessNo == 'YW') {
        await this.getplanList(this.form.connectionWayNo)
      }
      if (this.form.associatedBusinessNo == 'HD') {
        await this.getgetZsSystemActivityData()
      }
    },

    async getbessusinList(associatedBusinessNo) {
      await QmyxApi.bessusinList({
        pageNum: 1,
        pageSize: 999,
        associatedBusinessNo,
      }).then((res) => {
        this.bessusinList = res.rows
        this.setsanjilist(res.rows)
      })
    },

    async getplanList(associatedBusinessNo) {
      await QmyxApi.planList({
        pageNum: 1,
        pageSize: 999,
        connectionWayNo: associatedBusinessNo,
      }).then((res) => {
        this.planList = res.rows
        this.setsanjilist(res.rows)
      })
    },

    async getmodelList(associatedBusinessNo) {
      await QmyxApi.modelList({
        pageNum: 1,
        pageSize: 999,
        associatedBusinessNo,
      }).then((res) => {
        this.modelList = res.rows
        this.setsanjilist(res.rows)
      })
    },

    async getgetZsSystemActivityData() {
      await QmyxApi.getZsSystemActivityData({ pageNum: 1, pageSize: 999 }).then(
        (res) => {
          this.getZsSystemActivityData = res.rows
          this.setsanjilist(res.rows)
        }
      )
    },

    setsanjilist(list) {
      //
      this.sanjilist = list.map((val) => {
        const associationModeId =
          val.associationModeId ||
          val.id ||
          val.seckillId ||
          val.connectionWayNo
        const associationModeName =
          val.associationModeName ||
          val.value ||
          val.seckillName ||
          val.connectionWayName
        const returnbody = {
          associationModeId,
          associationModeName,
        }
        this.sanjimap[associationModeId] = returnbody
        this.sanjimap2[associationModeName] = returnbody
        return returnbody
      })
    },

    sanjichange() {
      this.form.associationModeDto = this.select.map((val) => {
        return this.sanjimap[val]
      })
    },

    selectfanganyongjin(row) {
      this.form.commissionId = row.commissionPlanId
      this.planName = row.planName
      this.shoufananyongjin = false
    },
  },
}
</script>
